var util = require('../../../utils/util.js');
var api = require('../../../config/api.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: "",
    productPic: "",
    price: "10999.00",//商品价格
    inventory: 0, //库存数量
    payNum: 0,//已售人数
    specText: "6.5英寸视网膜全面屏，面容ID", //规格
    iosNumber:0,

    windowWidth: 0, //屏幕宽度
    windowHeight: 0,//屏幕高度
    contentHeight: 600,//内容高度
    thinkList: [], //文字超出换行处理
    lineHeight: 30, //固定值
    delPrice: "12999.00",//划线价
    canvasUrl: "../../../images/share.png", //canvas李彪
    canvasBg: "../../../images/share.png",
    qrCode: "../../images/test2.jpeg", //小程序码https图片路径
    goodsInfoImg: "../../images/test.jpg",  //商品图片
    bcImg: "https://knowif.oss-cn-beijing.aliyuncs.com/5591CF4C3D1343429BC2D561B6D3DC19.PNG",//背景图片
    canvasShow: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      id: options.id
    });
    //获取详情数据
    this.getshopData();
    let that = this;
    //获取设备信息高度。计算出其他的高度等
    wx.getSystemInfo({
      success: function (res) {
        // //区分ios 和安卓坐标
        // if (res.model.indexOf('iPhone')>0){
        //   that.setData({
        //     iosNumber:-4
        //   })
        // }
        let windowWidth = 350;
        let windowHeight = 600
        that.setData({
          realWindowWidth: res.windowWidth,
          windowWidth: windowWidth,
          windowHeight: windowHeight,
          normalPageX:
            (res.windowWidth - windowWidth*0.84) / 2, //左边文本图片X轴位置
          boxWidth: windowWidth * 0.84, //分享图片box宽度
          boxheight: windowWidth * (0.222 + 0.72 + 0.192) + 60, //分享图片box高度
          boxPageY: windowWidth * 0.081, //boxY轴位置
          imgWidth: 200, //商品图片宽度
          imgHeight: 200, //商品图片高度
          pricePageY: windowHeight * 0.5 + 1, //价格的高度
          inventoryPageY: windowHeight * 0.5 - 3, //库存
          payNumPageY: windowHeight *0.5 - 3, //已售人数
          imgPageY: windowWidth * 0.25, //商品图片Y轴位置
          titlePageY: windowWidth * 0.222 + windowWidth * 0.72  //标题Y轴位置
        });
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: "知识鸭",
      imageUrl: this.data.canvasUrl,
      path: "/pages/shop/shopDetail/shopDetail"
    }
  },
  /**获取数据 */
  getshopData() {
    let that = this;
    util.request(`${api.ShopShopDetail}/${this.data.id}`, 'GET').then(function (res) {
      if (res.code === 200) {
        that.setData({
          productPic: res.result.productPic, //商品封面图，
          price: res.result.price, //商品价格
          inventory: res.result.inventory, //库存
          payNum: res.result.payNum, //已售人数
          specText: res.result.productName //商品名字
        })
      }
    }).then(() => { that.getTempFile() })
  },
  //临时背景图
  getTempFile: function () {
    let that = this;
    wx.downloadFile({
      url: that.data.bcImg,
      success: function (res) {
        that.setData({
          bcImg: res.tempFilePath
        });
        that.getShopFile()
      },
      fail: function (err) { }
    });
  },
  //获取商品信息图片
  getShopFile(){
    let that = this;
    wx.downloadFile({
      url: that.data.productPic,
      success: function (res) {
        that.setData({
          productPic: res.tempFilePath
        });
        that.getData(that)
      },
      fail: function (err) { }
    });
  },
  getData: function (that) {
    let i = 0;
    let lineNum = 1;
    let thinkStr = "";
    let thinkList = [];
    for (let item of that.data.specText) {
      if (item === "\n") {
        thinkList.push(thinkStr);
        thinkList.push("a");
        i = 0;
        thinkStr = "";
        lineNum += 1;
      } else if (i === 21) {
        thinkList.push(thinkStr);
        i = 1;
        thinkStr = item;
        lineNum += 1;
      } else {
        thinkStr += item;
        i += 1;
      }
    }
    thinkList.push(thinkStr);
    that.setData({
      thinkList: thinkList
    });
    that.createNewImg(lineNum);
  },
  //画矩形，也是整块画布的大小，宽度是屏幕宽度，高度根据内容多少来动态设置。
  drawSquare: function (ctx, height) {
    let that = this;
    // ctx.rect(
    //   that.data.windowWidth * 0.08,
    //   that.data.boxPageY,
    //   that.data.boxWidth,
    //   height
    // );
    // ctx.setFillStyle("#fecc72");
    // ctx.fill();
    //绘制背景图片
    ctx.drawImage(
      that.data.bcImg,
      that.data.normalPageX,
      that.data.boxPageY,
      that.data.boxWidth,
      that.data.boxheight
    );
    //绘制商品图片
    ctx.drawImage(
      that.data.productPic,
      (that.data.realWindowWidth - 170)/2 ,
      that.data.boxPageY + 70,
      170,
      170
    );
  },
  // 设置文字大小，并填充颜色。
  drawFont: function (ctx, specText, height) {
    let that = this;
    let str = that.data.specText;
    let firstline;
    let secondline;
    //一行显示14个字，超过一行时
    if (str.length > 18) {
      //第一行截取前14个字符
      firstline = str.substring(0, 18);
      //两行都显示不下
      if (str.length > 46) {
        secondline = str.substr(18, 18) + "...";
      } else {
        //第二行取剩下的
        secondline = str.substr(18, str.length - 18);
      }
    } else {
      //一行就能显示时候
      firstline = str;
    }

    ctx.setFontSize(12);
    ctx.setFillStyle("#000");
    ctx.fillText(firstline, (that.data.realWindowWidth - 170) / 2 - 10, that.data.titlePageY - 10);
    if (secondline) {
      ctx.setFontSize(12);
      ctx.setFillStyle("#333");
      ctx.fillText(
        secondline,
        (that.data.realWindowWidth - 170) / 2 - 10,
        that.data.titlePageY + 7
      );
    }
    if (that.data.specText) {
      ctx.setFontSize(12);
      ctx.setFillStyle("#ff5507");
      ctx.fillText(
        that.data.specText,
        (that.data.realWindowWidth - 170) / 2 - 15,
        that.data.specPageY + 18
      );
    }
    //绘制价格
    if (that.data.price) {
      ctx.setFontSize(12);
      ctx.setFillStyle("#ff5507");
      ctx.fillText(
        that.data.price,
        (that.data.realWindowWidth - 170) / 2 - 13,
        that.data.pricePageY
      );
    }
    //库存
    if (that.data.inventory) {
      ctx.setFontSize(8);
      ctx.setFillStyle("#ff8045");
      ctx.fillText(
        `库存：${that.data.inventory}`,
        (that.data.realWindowWidth) / 2 - 7 ,
        that.data.inventoryPageY 
      );
    }
    //已售人数
    if (that.data.payNum) {
      ctx.setFontSize(8);
      ctx.setFillStyle("#ff8045");
      ctx.fillText(
        `已售：${that.data.payNum}`,
        (that.data.realWindowWidth) / 2  + 58,
        that.data.payNumPageY 
      );
    }
  },
  // 根据文字多少动态计算高度，然后依次画出矩形，文字，横线和小程序码。
  createNewImg: function (lineNum) {
    let that = this;
    let ctx = wx.createCanvasContext("myCanvas");
    let contentHeight = that.data.boxheight + 20;
    that.drawSquare(ctx, contentHeight);
    that.setData({
      contentHeight: contentHeight
    });
    let height = 100;
    for (let item of that.data.thinkList) {
      if (item !== "a") {
        that.drawFont(ctx, item, height);
        height += that.data.lineHeight;
      }
    }
    //商品图片
    ctx.drawImage(
      that.data.goodsInfoImg,
      that.data.normalPageX,
      that.data.imgPageY,
      that.data.imgWidth,
      that.data.imgWidth
    );
    ctx.draw(false, setTimeout(function () {
      that.saveShareImg();
    }, 1000))
  },

  // 保存图片
  savePic: function () {
    let that = this;
    wx.canvasToTempFilePath({
      x: 0,
      y: 50,
      width: that.data.windowWidth * 2,
      height: that.data.contentHeight * 2,
      canvasId: "myCanvas",
      success: function (res) {
        wx.hideLoading();
        var tempFilePath = res.tempFilePath;
        that.setData({
          canvasUrl: tempFilePath
        })
      }
    });
  },
  //点击保存到相册
  saveShareImg: function () {
    var that = this;
    wx.showLoading({
      title: '正在保存',
      mask: true,
    })
    that.setData({
      canvasShow: true
    })
    wx.canvasToTempFilePath({
      canvasId: 'myCanvas',
      success: function (res) {
        wx.hideLoading();
        var tempFilePath = res.tempFilePath;
        wx.saveImageToPhotosAlbum({
          filePath: tempFilePath,
          success(res) {
            // utils.aiCardActionRecord(19);
            wx.showModal({
              content: '图片已保存到相册，赶紧晒一下吧~',
              showCancel: false,
              confirmText: '好的',
              confirmColor: '#333',
              success: function (res) {
                if (res.confirm) { }
              },
              fail: function (res) { }
            })
          },
          fail: function (res) {
            wx.showToast({
              title: res.errMsg,
              icon: 'none',
              duration: 2000
            })
          }
        })
      },
      fail: function (err) {
        wx.hideLoading();
        if (err.errMsg) {//重新授权弹框确认
          wx.showModal({
            title: '提示',
            content: '您好,请先授权，在保存此图片。',
            showCancel: false,
            success(res) {
              if (res.confirm) {//重新授权弹框用户点击了确定benUrl 
                wx.openSetting({//进入小程序授权设置页面
                  success(settingdata) {
                    console.log(settingdata)
                    if (settingdata.authSetting['scope.writePhotosAlbum']) {//用户打开了保存图片授权开关
                      wx.saveImageToPhotosAlbum({
                        filePath: tempFilePath,
                        success: function (data) {
                          wx.showToast({
                            title: '保存成功',
                            icon: 'success',
                            duration: 2000
                          })
                        },
                      })
                    } else {//用户未打开保存图片到相册的授权开关
                      wx.showModal({
                        title: '温馨提示',
                        content: '授权失败，请稍后重新获取',
                        showCancel: false,
                      })
                    }
                  }
                })
              }
            }
          })
        }
      }
    })
  }
})